
import 'dart:io';
import 'dart:typed_data';

import 'package:baselib/utils/gallery_camera_pick_util.dart';
import 'package:baselib/utils/keyboard_util.dart';
import 'package:baselib/utils/load_util.dart';
import 'package:baselib/utils/log_util.dart';
import 'package:baselib/utils/navigator_util.dart';
import 'package:baselib/utils/time_util.dart';
import 'package:baselib/utils/toast_util.dart';
import 'package:baselib/widgets/dialog_util.dart';
import 'package:baselib/widgets/select_photo_camera_alert_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:framelib/base/base_view_model.dart';
import 'package:framelib/config/api_config.dart';
import 'package:framelib/config/route_config.dart';
import 'package:framelib/net/baseentity.dart';
import 'package:framelib/utils/nim_sdk_util.dart';
import 'package:framelib/utils/oss_util.dart';
import 'package:framelib/utils/select_util.dart';
import 'package:framelib/utils/string_util.dart';
import 'package:framelib/widgets/page_widget.dart';
import 'package:get/state_manager.dart';
import 'package:get/get.dart';
import 'package:module_business/module_comm/model/country_entity.dart';
import 'package:module_business/module_comm/model/user_entity.dart';
import 'package:module_business/module_comm/model/user_params_model.dart';
import 'package:module_business/module_comm/service/module_comm_service.dart';

class RegisterInfoViewModel extends BaseViewModel<ModuleCommService>{
  ModuleCommService moduleCommService;
  Map<String,dynamic> arguments;
  String iconPath;
  String nickName;
  String birth;
  String countryId;
  File iconFile;

  int selectedGenderIndex = 0;
  //国家集合
  List<CountryEntity> countryEnties = [];

  @override
  ModuleCommService createService() =>moduleCommService = ModuleCommService();

  @override
  void onInit() {
    //设置默认值
    arguments = Get.arguments??{};
    print('RegisterInfoViewModel-->arguments=$arguments');
    super.onInit();
    //获取国家数据
    getCountryDatas();
  }


  inputChanged(String value, int index) {
    switch(index){
      case 0:
        nickName=value?.trim();
        break;
    }
  }

  isValidate() {
    if((iconPath??'').isEmpty){
      ToastUtil.toast(StringUtil.instance.Select_your_icon);
      return false;
    }
    if((nickName??'').isEmpty){
      ToastUtil.toast(StringUtil.instance.Input_your_nick_name);
      return false;
    }
    if((birth??'').isEmpty){
      ToastUtil.toast(StringUtil.instance.Select_your_birth);
      return false;
    }
    if((countryId??'').isEmpty){
      ToastUtil.toast(StringUtil.instance.Select_your_country);
      return false;
    }
    return true;
  }

  toRegisterSelectFavoritePage() async{
    if(!isValidate())return;
    // NavigatorUtil.pushByName(RouteConfig.registerSelectFavoritePage);
    Map<String,dynamic> upData={
      'icon':iconPath,
      'nickname':nickName,
      'countryId': countryId,
      'birthday':birth,
      'gender': selectedGenderIndex+1,
    };
    LoadUtil.showLoad();
    BaseEntity baseEntity = await moduleCommService.api_user_saveUserInfo(parmsMap: upData);
    KeyBoardUtil.downKeyBoard();
    LoadUtil.hideLoad();
    if (baseEntity?.code == ApiConfig.SUCCESS_CODE) {
      UserEntity userEntity = baseEntity?.result;
      if(userEntity!=null){
        var valid = userEntity.valid??(-1);
        UserParamsModel.instance
            .setToken(userEntity.token).setImToken(userEntity.imToken).setYxAccid(userEntity.yxAccid)
            .setUserId('${userEntity.userId}')
            .setUserEntity(userEntity);
        var niLoginResult = await NIMSDKUtil.instance.login(account: userEntity.yxAccid,token: userEntity.imToken);
        if (niLoginResult.isSuccess)UserParamsModel.instance.setSelfNIMUser(
            userIdTemp: '${userEntity.yxAccid??''}',nickTemp: '${userEntity?.nickname??''}',
            avatarTemp: '${userEntity?.icon??''}', genderTemp: userEntity?.gender??0,
            emailTemp: '${UserParamsModel.instance.account??''}',birthTemp: '${userEntity?.birthday??''}'
        );
        NavigatorUtil.offNamed(RouteConfig.registerSelectFavoritePage);
      }
    } else {
      ToastUtil.toast(baseEntity?.message);
    }
  }

  onGenderItemPressed(int index) {
    print('onGenderItemPressed--->selectedGenderIndex=$index');
    selectedGenderIndex = index;
    update();
  }
  //选择日历
  onBirthPressed() {
    SelectUtil.showDatetimePicker(
      Get.context,
      onConfirm: (DateTime birthday){
        print('birthday--->$birthday');
        birth = TimeUtils.forMatTimeByDateTime(birthday,format: 'yyyy-MM-dd');
        update();
      }
    );
  }
  //选择国家
  onCountryPressed() {
    SelectUtil.commSelect(
      datas: (countryEnties??[]).map((e) => e?.en).toList(),
      initIndex: (countryEnties??[]).indexWhere((element) => (element?.en==countryId)),
      onCancel: ()=>NavigatorUtil.goBack(),
      onConfirm: (index){
        NavigatorUtil.goBack();
        if(index==(-1))return;
        countryId = countryEnties[index].en;
        update();
      }
    );
  }

  onIconPressed() async{
    iconFile = await GalleryCameraPickUtil.instance.selectPicture();
    if(iconFile==null)return;
    LoadUtil.showLoad(loadingText: '${StringUtil.instance.Uploading}...');
    OssUtil.instance.upload(iconFile, complete: (path,isUpload){
      LoadUtil.hideLoad();
      iconPath = path;
      update();
    });
  }
  //获取国家数据
  void getCountryDatas() async{
    BaseEntity baseEntity = await ModuleCommService().api_index_getCountryList();
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      List<CountryEntity> countrysTemp=baseEntity?.result??[];
      if((countrysTemp).isNotEmpty){
        countryEnties.clear();
        countryEnties.addAll(countrysTemp);
        update();
      }
    }
  }

}
